<template>
  <div>
    <div class="panel">
      <div class="panel-header">
        {{ $route.params.actId ? $route.meta.title : '编辑外部活动' }}
      </div>
      <i-form
        ref="form"
        :items="formItems"
        :model="form"
        :rules="rules"
        :label-width="240"
        label-position="left"
      >
        <template slot="actStartTime">
          <el-form-item
            label="开始时间"
            prop="actStartTime"
            class="is-required"
          >
            <date-picker
              ref="actStartTime"
              type="datetime"
              v-model="actStartTime"
              format="YYYY-MM-DD HH:mm"
              placeholder="请选择开始时间"
              :disabled-date="disabledActStartDate"
              :time-picker-options="actStartTimePicker"
              @change="handleActStartChange"
              @pick="handleActStartPick"
              @clear="handleActStartClear"
              :renderInputText="renderActStartInputText"
            >
            </date-picker>
          </el-form-item>
        </template>
        <template slot="actEndTime">
          <el-form-item label="结束时间" prop="actEndTime" class="is-required">
            <date-picker
              ref="actEndTime"
              type="datetime"
              v-model="actEndTime"
              format="YYYY-MM-DD HH:mm"
              placeholder="请选择结束时间"
              :disabled-date="disabledActEndDate"
              :time-picker-options="actEndTimePicker"
              @change="handleActEndChange"
              @pick="handleActEndPick"
              @clear="handleActEndClear"
              :renderInputText="renderActEndInputText"
            ></date-picker>
          </el-form-item>
        </template>
        <template slot="pushFailMessage">
          <el-form-item label="推送领取失败信息" prop="pushFailMessage">
            <el-checkbox
              v-model="form.pushFailMessage"
              :true-label="1"
              :false-label="0"
            >
            </el-checkbox>
          </el-form-item>
        </template>
        <template slot="timecard">
          <el-form-item
            class="is-required timecard-item"
            :label="form.exActType === 1 ? '时长卡规格' : '和能量规格'"
          >
            <div class="timecard-wrapper">
              <div class="timecard-input">
                <div
                  class="timecard-input__item"
                  v-for="(item, index) in timecardArr"
                  :key="index"
                >
                  <div class="timecard-input__cell">
                    {{
                      form.exActType === 1
                        ? '请输入时长卡时长：'
                        : '请输入和能量数量：'
                    }}
                    <el-input
                      v-model.number="item.timeCardDuration"
                      class="v-validate"
                      v-validate="hourRules"
                    ></el-input>
                    {{ form.exActType === 1 ? '小时，' : '枚，' }}
                  </div>
                  <div class="timecard-input__cell">
                    {{
                      form.exActType === 1 ? '时长卡有效期：' : '和能量有效期：'
                    }}

                    <el-input
                      class="v-validate"
                      v-model.number="item.timeCardLimit"
                      placeholder="无限"
                      v-validate="periodRules"
                    ></el-input>
                    天，
                  </div>
                  <div class="timecard-input__cell">
                    总价值：
                    <el-input
                      v-model="item.timeCardMoney"
                      class="v-validate"
                      v-validate="timecardRules"
                    ></el-input>
                    元，
                  </div>
                  <div class="timecard-input__cell">
                    平台分成：
                    <el-input
                      v-model="item.timeCardPlatformMoney"
                      class="v-validate"
                      v-validate="timecardRules"
                    ></el-input>
                    元，
                  </div>
                  <div class="timecard-input__cell">
                    代理商分成：
                    <el-input
                      v-model="item.timeCardAgentMoney"
                      class="v-validate"
                      v-validate="timecardRules"
                    ></el-input>
                    元
                  </div>
                </div>
              </div>
              <div class="btn">
                <i
                  class="el-icon-remove"
                  v-if="timecardArr.length > 1"
                  @click="deleteTimecard"
                ></i>
                <i
                  class="el-icon-circle-plus"
                  v-if="timecardArr.length < 8"
                  @click="addTimecard"
                ></i>
              </div>
            </div>
          </el-form-item>
        </template>
        <template slot="scope">
          <el-form-item
            :label="form.exActType === 1 ? '活动范围' : '参与此活动的代理商'"
            prop="scope"
            class="is-required"
          >
            <TableSearch
              ref="tableSearch"
              class="scope-table"
              :page-name-display="false"
              :formItemsInline="formItemsInline"
              :columns="columns"
              :tableData="tableData"
              :form="formInline"
              @handleTableData="handleTableData"
              @reset="reset"
            >
              <template slot="tableSearchHeader">
                <div class="table-outside-header">
                  <div class="search-result-count">
                    当前搜索结果<strong>{{ tableData.totalCount || 0 }}</strong
                    >条
                  </div>
                  <a class="preview-btn" @click="handlePreview"
                    >预览所有电站<span class="highlight"
                      >(已选择电站：{{ stationCount }}个)</span
                    ></a
                  >
                </div>
              </template>
              <el-table-column slot="radio">
                <template #default="{ row }">
                  <el-radio
                    v-model="form.actMchId"
                    :label="row.id"
                    @change="() => handleRadioChange(row)"
                    >{{&nbsp;}}</el-radio
                  >
                </template>
              </el-table-column>
            </TableSearch>
          </el-form-item>
        </template>
      </i-form>
    </div>
    <div class="panel-btn-wrapper">
      <el-button type="success" @click="handleSubmit" v-checkSubmit
        >确认</el-button
      >
      <el-button type="warning" @click="handleReset">重置</el-button>
    </div>
    <AllocStation
      v-if="allocStationVisible"
      @refreshTable="refreshTable"
      :visible.sync="allocStationVisible"
      :merchant-id="merchantId"
      :alloc-station-type="allocStationType"
      :select-stations="stations"
    />
  </div>
</template>
<script>
import dayjs from 'dayjs'
import DatePicker from 'vue2-datepicker'
import 'vue2-datepicker/index.css'
import 'vue2-datepicker/locale/zh-cn'
import TableSearch from '@/components/TableSearch'
import AllocStation from './components/AllocStation'
import {
  insertExActivity,
  systemUserList,
  selectExternalActivityDetail,
  updateExActivity,
} from '@/api/activity'
import { typeMap } from '@/utils/format'
import formatter from '@/utils/format'
import { validateMap } from '@/utils/validate'
import formValidate from '@/utils/validate'
export default {
  name: 'ExternalActivityAdd',
  components: { DatePicker, TableSearch, AllocStation },
  data() {
    return {
      showFilter: true,
      dateType: null,
      type: ['add', 'edit', 'copy']
        .filter((item) => this.$route.path.toLowerCase().includes(item))
        .join(),
      actStartTime: '',
      actEndTime: '',
      detail: null,
      allocStationVisible: false,
      merchantId: -1, //默认值
      allocStationType: 'select',
      mechantStationCount: 0,
      stations: [],
      stationCount: 0,
      form: {
        pushFailMessage: 1,
        exActType: 1,
      },
      formInline: {
        userName: '',
      },
      timecardArr: [
        {
          timeCardDuration: '',
          timeCardLimit: '',
          timeCardMoney: '',
          timeCardPlatformMoney: '',
          timeCardAgentMoney: '',
        },
      ],
      actStartTimePicker: {
        start: '00:00',
        step: '00:05',
        end: '23:55',
      },
      actEndTimePicker: {
        start: '00:00',
        step: '00:05',
        end: '23:55',
      },
      tableData: {},
      formItemsInline: [
        {
          type: 'text',
          value: 'userName',
          placeholder: '请输入代理商名称',
          clearable: true,
        },
      ],
      columns: [
        {
          slot: 'radio',
        },
        {
          label: '代理商名称',
          prop: 'userName',
        },
        {
          label: '手机号',
          prop: 'mobile',
        },
        {
          label: '管理员姓名',
          prop: 'name',
        },
        {
          label: '商户类别',
          prop: 'type',
          formatter: (row) => {
            return typeMap.userType[row.type]
          },
        },
        {
          label: '支付方式',
          prop: 'paymentChannels',
          formatter,
        },
        {
          label: '所辖电站',
          prop: 'stationCount',
        },
        {
          label: '操作',
          buttons: [
            {
              label: '选择部分电站',
              click: (row) => {
                this.allocStationType = 'add'
                this.allocStationVisible = true
                this.merchantId = row.id
                this.mechantStationCount = row.stationCount
                if (this.form.actMchId !== this.merchantId)
                  this.stationCount = row.stationCount
                this.$set(this.form, 'actMchId', row.id)
                this.$set(this.form, 'actMchName', row.userName)
              },
            },
          ],
          hidden: () => {
            return this.form.exActType === 2
          },
        },
      ],
      formItems: [
        {
          label: '活动类型',
          type: 'radio',
          value: 'exActType',
          required: true,
          options: () => {
            return typeMap
              .radioOptions([], 'externalActivityType')
              .map(({ text, label }) => {
                return {
                  text: text + '活动',
                  label: label,
                }
              })
          },
          change: () => {
            this.handelExActTypeChange()
          },
        },
        {
          label: '活动名称',
          type: 'text',
          value: 'actName',
          required: true,
          maxlength: 60,
          showWordLimit: true,
        },
        {
          label: '活动描述',
          type: 'text',
          value: 'actDescription',
          required: true,
          maxlength: 100,
          showWordLimit: true,
        },
        {
          label: '领取失败提示',
          type: 'text',
          value: 'failMessage',
          required: true,
          maxlength: 100,
          showWordLimit: true,
          ifRender: () => {
            return this.form.exActType === 1
          },
        },
        {
          slot: 'actStartTime',
        },
        {
          slot: 'actEndTime',
        },
        {
          label: '外部代理商唯一标识',
          type: 'text',
          value: 'exMchId',
          required: true,
          placeholder: '代理商唯一标识',
          maxlength: 11,
          showWordLimit: true,
        },
        {
          label: '外部代理商信息',
          type: 'text',
          value: 'exMchName',
          placeholder: '代理商信息',
          maxlength: 20,
          showWordLimit: true,
        },
        {
          label: '联系方式',
          type: 'text',
          value: 'exMchMobile',
          placeholder: '',
        },
        {
          label: 'APPID',
          type: 'text',
          value: 'appid',
          required: true,
          maxlength: 16,
          showWordLimit: true,
        },
        {
          label: '时长卡类型',
          type: 'select',
          value: 'timeCardType',
          placeholder: '请选择时长卡类型',
          required: true,
          options: typeMap.selectOptions([], 'externalTimeCardType'),
          ifRender: () => {
            return this.form.exActType === 1
          },
        },
        {
          label: '第三方平台查询用户接口url',
          type: 'text',
          value: 'queryUserUrl',
          required: true,
          placeholder: '',
          maxlength: 200,
          showWordLimit: true,
          ifRender: () => {
            return this.form.exActType === 1
          },
        },
        {
          label: '第三方平台推送时长卡状态接口url',
          type: 'text',
          value: 'pushTimecardStatusUrl',
          required: true,
          placeholder: '',
          maxlength: 200,
          showWordLimit: true,
          ifRender: () => {
            return this.form.exActType === 1
          },
        },
        {
          label: '第三方平台【查看更多】按钮url',
          type: 'text',
          value: 'showMoreUrl',
          required: true,
          placeholder: '',
          maxlength: 200,
          showWordLimit: true,
          ifRender: () => {
            return this.form.exActType === 1
          },
        },
        {
          label: '发放时长卡按阶梯功率扣费',
          type: 'select',
          value: 'powerCharging',
          placeholder: '请选择时长卡类型',
          required: true,
          options: [
            {
              label: '否',
              value: false,
            },
            {
              label: '是',
              value: true,
            },
          ],
          ifRender: () => {
            return this.form.exActType === 1
          },
        },
        {
          slot: 'timecard',
        },
        {
          slot: 'pushFailMessage',
          ifRender: () => {
            return this.form.exActType === 1
          },
        },
        {
          label: '提示',
          type: 'textarea',
          value: 'agreement',
          required: true,
          placeholder: '请输入协议内容',
          maxlength: 200,
          showWordLimit: true,
          ifRender: () => {
            return this.form.exActType === 1
          },
        },
        {
          slot: 'scope',
        },
      ],
      hourRules: [
        {
          required: true,
          msg: '该项为必填项',
        },
        validateMap.validatePositiveInteger,
        {
          validator: (val) => {
            if (this.form.exActType === 1) {
              return val <= 8640
            } else {
              return val <= 99999
            }
          },
          msg: () =>
            this.form.exActType === 1 ? '不能大于8640！' : '不能大于99999',
        },
      ],
      timecardRules: [
        {
          required: true,
          msg: '该项为必填项',
        },
        validateMap.validatePrecisionTwo,
        {
          validator: (val) => {
            return val <= 999
          },
          msg: '不能大于999！',
        },
      ],
      periodRules: [
        {
          validator: (value) => {
            if (value) {
              let reg = /^(?!0)\d{1,3}$/
              return reg.test(value)
            }
            return true
          },
          msg: '大于0小于999的整数',
        },
      ],
      rules: {
        actName: [
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
        actDescription: [
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
        failMessage: [
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
        exMchName: [
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
        exMchMobile: [
          {
            validator: formValidate('validateServiceMobile'),
            trigger: ['change', 'blur'],
          },
        ],
        queryUserUrl: [
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
        pushTimecardStatusUrl: [
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
        showMoreUrl: [
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
        appid: [
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
        agreement: [
          {
            validator: formValidate('validateExplanation'),
            trigger: ['change', 'blur'],
          },
        ],
        actStartTime: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.actStartTime) {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        actEndTime: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.actEndTime) {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
        scope: [
          {
            validator: (rule, value, callback) => {
              if (!this.form.actMchId) {
                return callback(new Error('该项为必填项'))
              } else {
                return callback()
              }
            },
            trigger: ['change', 'blur'],
          },
        ],
      },
    }
  },
  watch: {
    'form.actStartTime': {
      handler(val, oldVal) {
        if (val !== oldVal) {
          this.$refs.form && this.$refs.form.validateField('actStartTime')
        }
      },
    },
    'form.actEndTime': {
      handler(val, oldVal) {
        if (val !== oldVal) {
          this.$refs.form && this.$refs.form.validateField('actEndTime')
        }
      },
    },
    'form.actMchId': {
      handler(val, oldVal) {
        console.log(val)
        console.log(oldVal)
        if (val !== oldVal) {
          this.$refs.form && this.$refs.form.validateField('scope')
        }
      },
    },
  },
  methods: {
    disabledActStartDate(date) {
      return (
        date < new Date().setHours(0, 0, 0, 0) ||
        date > new Date(this.form.actEndTime).setHours(0, 0, 0, 0)
      )
    },
    disabledActEndDate(date) {
      return (
        date < new Date(this.form.actStartTime).setHours(0, 0, 0, 0) ||
        date < new Date().setHours(0, 0, 0, 0)
      )
    },
    handleActStartChange(val, type) {
      this.actStartateType = type
    },
    handleActStartPick(date) {
      let flag = date > new Date()
      this.actStartTimePicker.start = flag
        ? '00:00'
        : new Date().getHours() +
          ':' +
          Math.ceil(new Date().getMinutes() / 5) * 5
      if (this.form.actEndTime) {
        if (date < new Date(this.form.actEndTime).setHours(0, 0, 0, 0)) {
          this.actStartTimePicker.end = '23:55'
        } else {
          date = new Date(
            new Date(this.form.actEndTime).setMinutes(
              new Date(this.form.actEndTime).getMinutes() - 5
            )
          )
          this.actStartTimePicker.end =
            date.getHours() + ':' + date.getMinutes()
        }
      }
    },
    handleActStartClear() {
      this.form.actStartTime = ''
    },
    renderActStartInputText(val) {
      if (this.actStartateType === 'time') {
        this.form.actStartTime = Date.parse(val)
        return dayjs(this.form.actStartTime).format('YYYY-MM-DD HH:mm')
      } else {
        this.form.actStartTime = this.form.actStartTime
          ? dayjs(this.form.actStartTime).valueOf()
          : undefined
        return this.form.actStartTime
          ? dayjs(this.form.actStartTime).format('YYYY-MM-DD HH:mm')
          : undefined
      }
    },
    renderActEndInputText(val) {
      if (this.actEndDateType === 'time') {
        this.form.actEndTime = Date.parse(val)
        return dayjs(this.form.actEndTime).format('YYYY-MM-DD HH:mm')
      } else {
        this.form.actEndTime = this.form.actEndTime
          ? dayjs(this.form.actEndTime).valueOf()
          : undefined
        return this.form.actEndTime
          ? dayjs(this.form.actEndTime).format('YYYY-MM-DD HH:mm')
          : undefined
      }
    },
    handleActEndChange(val, type) {
      this.actEndDateType = type
    },
    handleActEndPick(date) {
      if (!this.form.actStartTime) {
        this.actEndTimePicker.start =
          date > new Date()
            ? '00:00'
            : new Date().getHours() +
              ':' +
              Math.ceil(new Date().getMinutes() / 5) * 5
      } else {
        if (date > new Date(this.form.actStartTime)) {
          this.actEndTimePicker.start = '00:00'
        } else {
          date = new Date(
            new Date(this.form.actStartTime).setMinutes(
              new Date(this.form.actStartTime).getMinutes() + 5
            )
          )
          this.actEndTimePicker.start =
            date.getHours() + ':' + date.getMinutes()
        }
      }
    },
    handleActEndClear() {
      this.form.actEndTime = ''
    },
    handelExActTypeChange() {
      this.form = Object.assign(
        {
          exActType: this.form.exActType,
          actName: this.form.actName,
          actDescription: this.form.actDescription,
          actStartTime: this.form.actStartTime,
          actEndTime: this.form.actEndTime,
          exMchId: this.form.exMchId,
          exMchName: this.form.exMchName,
          exMchMobile: this.form.exMchMobile,
          appid: this.form.appid,
        },
        this.form.exActType === 1 && { pushFailMessage: 1 }
      )
      this.formInline = {
        userName: '',
      }
      this.timecardArr = [
        {
          timeCardDuration: '',
          timeCardLimit: '',
          timeCardMoney: '',
          timeCardPlatformMoney: '',
          timeCardAgentMoney: '',
        },
      ]
      this.merchantId = -1 //默认值
      this.actMchName = ''
      this.allocStationType = 'add'
      this.mechantStationCount = 0
      this.stations = []
      this.stationCount = 0
    },
    addTimecard() {
      this.timecardArr.push({
        timeCardDuration: '',
        timeCardLimit: '',
        timeCardMoney: '',
        timeCardPlatformMoney: '',
        timeCardAgentMoney: '',
      })
    },
    deleteTimecard() {
      this.timecardArr.pop()
    },
    reset() {
      this.formInline = {
        userName: '',
      }
    },
    handleTableData(params) {
      systemUserList(params).then((res) => {
        this.tableData = {
          list: res.list,
          totalCount: res.totalAmount,
        }
      })
    },
    refreshTable(stations) {
      this.stations = stations
      this.stationCount = stations.length || this.mechantStationCount
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.validateField('scope')
      })
    },
    handlePreview() {
      if (!this.form.actMchId) {
        this.$message({
          type: 'warning',
          message: '选择代理商或选择代理商下面的电站才可预览！',
        })
        return
      }
      this.allocStationType = 'preview'
      this.allocStationVisible = true
    },
    handleRadioChange(row) {
      this.stationCount = row.stationCount
      this.stations = []
      this.merchantId = row.id
      this.$set(this.form, 'actMchId', row.id)
      this.$set(this.form, 'actMchName', row.userName)
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.validateField('scope')
      })
    },
    handleReset() {
      this.form = {
        pushFailMessage: 1,
        exActType: 1,
      }
      this.formInline = {
        userName: '',
      }
      this.timecardArr = [
        {
          timeCardDuration: '',
          timeCardLimit: '',
          timeCardMoney: '',
          timeCardPlatformMoney: '',
          timeCardAgentMoney: '',
        },
      ]
      this.merchantId = -1 //默认值
      this.actMchName = ''
      this.allocStationType = 'add'
      this.mechantStationCount = 0
      this.stations = []
      this.stationCount = 0
    },
    _handleTimecardArr() {
      return this.timecardArr
        .map((item) => {
          return (
            item.timeCardDuration +
            ',' +
            (item.timeCardLimit ? item.timeCardLimit : '') +
            ',' +
            item.timeCardMoney +
            ',' +
            item.timeCardPlatformMoney +
            ',' +
            item.timeCardAgentMoney
          )
        })
        .join(';')
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        const handler = {
          add: {
            fn: insertExActivity,
            message: '创建外部活动成功',
          },
          edit: {
            fn: updateExActivity,
            message: '编辑外部活动成功',
          },
          copy: {
            fn: insertExActivity,
            message: '复制外部活动成功',
          },
        }
        let params = Object.assign(
          {},
          this.form,
          {
            specification: this._handleTimecardArr(),
          },
          this.stations.length && {
            stationIds: this.stations
              .map((item) => {
                return item.id
              })
              .join(','),
          },
          this.type === 'edit' && { id: this.$route.params.exActId }
        ) //构建参数
        params.stations && delete params.stations
        handler[this.type].fn(params).then(() => {
          this.$message({
            type: 'success',
            message: handler[this.type].message,
          })
          this.$router.push('/activity/externalList')
        })
      })
    },
  },
  async created() {
    if (this.type !== 'add') {
      this.detail = await selectExternalActivityDetail({
        id: parseInt(this.$route.params.exActId),
      })
      this.form = this.detail
      this.merchantId = this.detail.actMchId //默认值
      this.stations = this.detail.stations
      this.stationCount = this.detail.stations.length
      if (this.detail.specification) {
        let timeCardArr = this.detail.specification.split(';')
        let tmpArr = []
        timeCardArr.forEach((item) => {
          let timeCard = item.split(',')
          tmpArr.push({
            timeCardDuration: timeCard[0],
            timeCardLimit: timeCard[1] ? timeCard[1] : '',
            timeCardMoney: timeCard[2],
            timeCardPlatformMoney: timeCard[3],
            timeCardAgentMoney: timeCard[4],
          })
        })
        this.timecardArr = tmpArr
      }
    }
  },
}
</script>
<style lang="scss" scoped>
.i-form {
  padding: 0 40px;
  &::v-deep .el-form-item.is-error .el-transfer-panel__body .el-input__inner,
  .el-form-item.is-error .el-textarea__inner {
    border-color: #d9d9d9;
  }
  &::v-deep .el-form-item.is-error .el-transfer-panel {
    border-color: #ff4d4f;
  }
  &::v-deep .el-form-item.is-error .mx-input {
    border-color: #ff4d4f;
  }
  &::v-deep .iform {
    margin-left: -20px !important;
  }
  .timecard-wrapper {
    display: flex;
    // .timecard-input {
    //   width: 95%;
    // }
    .timecard-input__item {
      display: flex;
      flex-wrap: wrap;
      margin-bottom: 24px;
      flex: 1 1 auto;
      &:last-child {
        margin-bottom: 0;
      }
      .timecard-input__cell {
        display: flex;
        .el-input {
          width: 150px;
        }
      }
    }
  }
  .table-outside-header {
    display: flex;
    justify-content: space-between;
  }
  .preview-btn {
    color: #005be5;
  }
  .highlight {
    color: #ff4d4f;
  }
  .scope-table {
    &::v-deep .form-wrapper,
    &::v-deep .table-wrapper {
      padding: 0;
    }
  }
}
</style>
